<?php

namespace app\common\cachemodel\acquired_astro;

use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

class AppAcquiredAstroAnswerRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_acquired_astro_answer_record';

    protected $cacheModel = 'acquired_astro.exercise_answer_record';

    /**
     * 新增 用户答题记录
     * @param $data
     * @return int
     */
    public function saveData($data)
    {
        try
        {
            if (isset($data['answer_data']) && is_array($data['answer_data']))
            {
                $data['answer_data'] = json_encode($data['answer_data'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['uid'])->rmCache();
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 更新 答题信息
     * @param int $uid
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function updateData(int $uid, int $id, array $data)
    {
        try
        {
            if (isset($data['answer_data']) && is_array($data['answer_data']))
            {
                $data['answer_data'] = json_encode($data['answer_data'], JSON_UNESCAPED_UNICODE);
            }
            $this->where(['id' => $id])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取 答题记录信息
     * @param int $uid
     * @return array|null
     * @throws \Exception
     */
    public function getUserAnswerData(int $uid)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->where(['uid' => $uid])->order('id desc')->findOrFail()->toArray();
                return $data;
            }
            catch (\Exception $e)
            {
                return [];
            }
        });

        if ($data)
        {
            $data = arrayKeyData2int($data, ['id', 'uid', 'type', 'index', 'num', 'record_id', 'create_time']);
            $data['answer_data'] = json_decode($data['answer_data'], true);
            return $data;
        } else
        {
            return null;
        }
    }

    /**
     * 获取 测试 答题 信息
     * @param array $testAnswerData
     * @return array
     * @throws \Exception
     */
    public function getQuestionAnswerDataResult(array $testAnswerData)
    {
        // 下一个题目 的题目数
        $nextIndex = $testAnswerData['index'] + 1;
        $categoryData = ZhunleappAstroExercise::getQuestionCategoryData();
        $nowCid = 0;    // 当前 题目分类
        $cIndex = 0;    // 当前 题目分类 题目索引
        $tmpNextIndex = $nextIndex;
        $resCategoryListData = [];
        foreach ($categoryData as $cid => $cname)
        {
            $nowQueNum = $testAnswerData['answer_data']["q{$cid}_num"];
            $cData = [
                'title' => $cname,
                'is_lock' => $nowQueNum > 0 ? 0 : 1,
            ];
            if ($tmpNextIndex <= $nowQueNum)
            {   // 当前 分类题目索引
                if (!$nowCid)
                {
                    $nowCid = $cid;
                    $cIndex = $tmpNextIndex - 1;
                    $cData['progress'] = (int)(($cIndex / $nowQueNum) * 100);
                } else
                {
                    $cData['progress'] = 0;
                }
            } else
            {
                if (!$nowCid)
                {
                    $tmpNextIndex -= $nowQueNum;
                    $cData['progress'] = 100;
                } else
                {
                    $cData['progress'] = 0;
                }
            }
            $resCategoryListData[] = $cData;
        }

        $qid = $testAnswerData['answer_data']["q{$nowCid}"][$cIndex];

        $questionData = (new ZhunleappAstroExercise())->getInfoById($qid);

        $topicOptionData = [
            [
                'text' => $questionData['option_a'],
                'value' => 'A',
            ],
            [
                'text' => $questionData['option_b'],
                'value' => 'B',
            ],
        ];

        shuffle($topicOptionData);
        $valueArray = ['A', 'B'];
        foreach ($topicOptionData as $index => $itemData)
        {
            $topicOptionData[$index]['text'] = $valueArray[$index] . '. ' . $itemData['text'];
        }

        $resData = [
            'index' => $nextIndex,
            'max_question' => $testAnswerData['num'],
            'tip' => '请以真实想法作答，不可反悔哦～',
            'category_list' => $resCategoryListData,
            'question' => $questionData['title'],
            'topic_option' => $topicOptionData,
        ];

        return $resData;
    }

    /**
     * 获取 测试题目ID
     * @param array $testAnswerData
     * @return int
     */
    public function getTestAnswerQid(array $testAnswerData)
    {
        // 下一个题目 的题目数
        $nextIndex = $testAnswerData['index'] + 1;
        $categoryData = ZhunleappAstroExercise::getQuestionCategoryData();
        $nowCid = 0;    // 当前 题目分类
        $cIndex = 0;    // 当前 题目分类 题目索引
        $tmpNextIndex = $nextIndex;
        foreach ($categoryData as $cid => $cname)
        {
            $nowQueNum = $testAnswerData['answer_data']["q{$cid}_num"];
            if ($tmpNextIndex <= $nowQueNum)
            {   // 当前 分类题目索引
                $nowCid = $cid;
                $cIndex = $tmpNextIndex - 1;
                break;
            } else
            {
                $tmpNextIndex -= $nowQueNum;
            }
        }

        return (int)($testAnswerData['answer_data']["q{$nowCid}"][$cIndex] ?? 0);
    }
}